<template>
  <div class="employee-container">
    <el-card class="employee-card">
      <!-- 顶部操作栏 -->
      <div class="header-actions">
        <div class="left">
          <span class="title">员工账号管理</span>
          <el-tag type="info" effect="plain" size="small">
            共 {{ total }} 个账号
          </el-tag>
        </div>
        <div class="actions">
          <el-input
            v-model="keyword"
            placeholder="搜索员工姓名/用户名"
            clearable
            style="width: 200px; margin-right: 16px"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增员工
          </el-button>
        </div>
      </div>

      <!-- 员工列表 -->
      <el-table
        v-loading="loading"
        :data="employeeList"
        border
        stripe
        style="margin-top: 20px"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column label="角色" min-width="150">
          <template #default="{ row }">
            <el-tag
              v-for="role in row.role"
              :key="role.id"
              :type="getRoleTagType(role.roleName)"
              class="mr-2"
            >
              {{ role.roleName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="头像" width="80" align="center">
          <template #default="{ row }">
            <el-avatar
              :size="40"
              :src="formatImageUrl(row.avatarUrl)"
              :alt="row.nickname"
            />
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" align="center">
          <template #default="{ row }">
            {{ maskPhone(row.phone) }}
          </template>
        </el-table-column>
        <el-table-column label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ row.gender === 1 ? "男" : "女" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="birthday"
          label="生日"
          width="120"
          align="center"
        />
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ maskEmail(row.email) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'danger'">
              {{ row.status === 0 ? "正常" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="updatedTime"
          label="更新时间"
          width="180"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.updatedTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="employeeFrom.page"
          v-model:page-size="employeeFrom.size"
          :total="total"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增员工' : '编辑员工'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="employeeForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="employeeForm.username"
            placeholder="请输入用户名"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input
            v-model="employeeForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="employeeForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select
            v-model="employeeForm.role"
            placeholder="请选择角色"
            multiple
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatarUrl">
          <el-input
            v-model="employeeForm.avatarUrl"
            placeholder="请输入头像URL"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="employeeForm.gender" placeholder="请选择性别">
            <el-option
              v-for="item in genderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="employeeForm.birthday"
            type="date"
            placeholder="请选择生日"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="employeeForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="employeeForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Search, Plus, Edit, Delete } from "@element-plus/icons-vue";
import { formatDateTime } from "@/utils/date";
import { formatImageUrl, maskPhone, maskEmail } from "@/utils/tools";
import { useUserStore } from "@/stores/user";
import {
  getEmployeeList,
  addEmployee,
  updateEmployee,
  deleteEmployee,
  updateEmployeeStatus,
  getEmployeeRoleDetail
} from "@/api/employee";
import { message } from "@/utils/message";

// 定义接口
interface Role {
  id: string;
  roleName: string;
  nickname: string;
  status: number;
  avatarUrl: string;
  count: string;
}

interface Employee {
  id: string;
  phone: string;
  nickname: string;
  username: string;
  role: Role[];
  avatarUrl: string;
  gender: number;
  birthday: string;
  email: string | null;
  status: number;
  updatedTime: string;
}

// 状态定义
const loading = ref(false);
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const formRef = ref<FormInstance>();
const total = ref(0);

// 表单数据
const employeeForm = reactive({
  id: "",
  phone: "",
  nickname: "",
  username: "",
  password: "",
  role: [] as string[],
  avatarUrl: "",
  gender: 0,
  birthday: "",
  email: "",
  status: 0,
  realName: ""
});

// 分页信息
const employeeFrom = reactive({
  page: 1,
  size: 10,
  message: "",
  gender: "",
  status: ""
});

// 表单校验规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
  ],
  realName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  role: [{ required: true, message: "请选择角色", trigger: "change" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
  ]
});

const userStore = useUserStore();

// 获取角色列表
const roleList = ref([]);

const getRoleList = async () => {
  const res = await getEmployeeRoleDetail();
  if (res.code === 200) {
    roleList.value = res.data;
  }
};

// 获取角色标签类型
const getRoleTagType = (roleName: string) => {
  switch (roleName) {
    case "摄影师":
      return "success";
    case "化妆师":
      return "warning";
    default:
      return "info";
  }
};

// 判断是否可以管理员工
const canManageEmployee = (employee: Employee | Record<string, never>) => {
  // 只有超级管理员可以管理员工账号
  return userStore.isSuperAdmin;
};

// 处理状态变更
const handleStatusChange = async (row: EmployeeData) => {
  if (!canManageEmployee(row)) {
    row.status = row.status === 1 ? 0 : 1; // 恢复状态
    ElMessage.error("只有超级管理员可以管理员工账号");
    return;
  }

  try {
    await updateEmployeeStatus(row.id, row.status);
    ElMessage.success("状态更新成功");
  } catch (error: any) {
    row.status = row.status === 1 ? 0 : 1; // 恢复状态
    ElMessage.error(error.message || "状态更新失败");
  }
};

// 新增员工
const handleAdd = () => {
  if (!canManageEmployee({})) {
    ElMessage.error("只有超级管理员可以管理员工账号");
    return;
  }

  dialogType.value = "add";
  resetForm();
  dialogVisible.value = true;
};

// 编辑员工
const handleEdit = (row: Employee) => {
  dialogType.value = "edit";
  Object.assign(employeeForm, {
    id: row.id,
    phone: row.phone,
    nickname: row.nickname,
    username: row.username,
    role: row.role.map(r => r.id),
    avatarUrl: row.avatarUrl,
    gender: row.gender,
    birthday: row.birthday,
    email: row.email || "",
    status: row.status,
    realName: row.nickname
  });
  dialogVisible.value = true;
};

// 删除员工
const handleDelete = (row: EmployeeData) => {
  if (!canManageEmployee(row)) {
    ElMessage.error("只有超级管理员可以管理员工账号");
    return;
  }

  ElMessageBox.confirm("确定要删除该员工账号吗？删除后不可恢复！", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteEmployee(row.id);
        ElMessage.success("删除成功");
        if (employeeList.value.length === 1 && employeeFrom.page > 1) {
          // 如果删除的是最后一条数据，跳转到上一页
          employeeFrom.page--;
        }
        loadData();
      } catch (error: any) {
        ElMessage.error(error.message || "删除失败");
      }
    })
    .catch(() => {});
};

// 重置表单
const resetForm = () => {
  Object.assign(employeeForm, {
    id: "",
    phone: "",
    nickname: "",
    username: "",
    password: "",
    role: [],
    avatarUrl: "",
    gender: 0,
    birthday: "",
    email: "",
    status: 0,
    realName: ""
  });
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true;
        const submitData = {
          ...employeeForm,
          password:
            dialogType.value === "add" ? employeeForm.password : undefined
        };

        if (dialogType.value === "add") {
          await addEmployee(submitData);
          ElMessage.success("添加成功");
        } else {
          await updateEmployee(submitData);
          ElMessage.success("更新成功");
        }
        dialogVisible.value = false;
        loadData();
      } catch (error: any) {
        ElMessage.error(
          error.message ||
            (dialogType.value === "add" ? "添加失败" : "更新失败")
        );
      } finally {
        loading.value = false;
      }
    }
  });
};

// 处理分页
const handleSizeChange = (val: number) => {
  employeeFrom.size = val;
  employeeFrom.page = 1;
  loadData();
};

const handleCurrentChange = (val: number) => {
  employeeFrom.page = val;
  loadData();
};

const employeeList = ref<Employee[]>([]);

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const { data } = await getEmployeeList(employeeFrom);
    if (data) {
      employeeList.value = data.result;
      total.value = data.total;
    }
  } catch (error) {
    ElMessage.error("获取员工列表失败");
  } finally {
    loading.value = false;
  }
};

// 修改角色选项，移除管理员选项
const roleOptions = [
  { label: "运营", value: "operator" },
  { label: "客服", value: "customer_service" },
  { label: "摄影师", value: "photographer" },
  { label: "化妆师", value: "makeup_artist" }
];

// 添加搜索功能
const keyword = ref("");

const handleSearch = async () => {
  employeeFrom.page = 1;
  await loadData();
};

// 添加性别选项
const genderOptions = [
  { label: "女", value: 0 },
  { label: "男", value: 1 }
];

// 初始化
onMounted(() => {
  getRoleList();
  loadData();
});
</script>

<style lang="scss" scoped>
.employee-container {
  padding: 24px;
  background: var(--el-bg-color-page);

  .employee-card {
    .header-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left {
        display: flex;
        align-items: center;
        gap: 12px;

        .title {
          font-size: 18px;
          font-weight: 600;
          color: var(--el-text-color-primary);
        }
      }
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
